<template>

 <el-form :inline="true" :model="formInline" class="demo-form-inline">
    <el-form-item label="用户名称">
      <el-input v-model="formInline.name" placeholder="请输入用户名称" clearable />
    </el-form-item>
    
    
    <el-form-item>
      <el-button type="primary" @click="onSubmit">查询</el-button>
    </el-form-item>
  </el-form>

   <el-form-item>
      <el-button type="success" @click="dialogFormVisible = true">新增</el-button>
    </el-form-item>
  <el-table :data="tableData" border style="width: 100%">
    <el-table-column prop="id" type="index" label="用户编号" />
    <el-table-column prop="name" label="用户名称"/>
     <el-table-column prop="password" label="密码">
        <template v-slot="a">
            <span>*****</span>
        </template>
     </el-table-column>
    <el-table-column prop="roleName" label="角色"/>
    <el-table-column prop="state" label="状态" width="120" align="center">
      <template v-slot="scope">
        <el-switch
          v-model="scope.row.state"
          @change="handleStateChange(scope.row)"
          active-text="启用"
          inactive-text="禁用"
          :active-value="true"
          :inactive-value="false"
        />
      </template>
    </el-table-column>
    <el-table-column label="操作" width="220" align="center">
        <template v-slot="a">
             <el-button type="primary" size="small" @click="find(a.row)">编辑</el-button>
             <el-button type="danger" size="small" @click="handleDelete(a.row)" :icon="Delete">删除</el-button>
        </template>
    </el-table-column>
  </el-table>

  <!-- 分页 -->
  <div class="demo-pagination-block">
    <el-pagination
      v-model:current-page="formInline.pageIndex"
      v-model:page-size="formInline.pageSize"
      :page-sizes="[3, 6, 7, 9]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagin.totaleCount"
    />
  </div>

 <!-- 新增 -->
  <el-dialog v-model="dialogFormVisible" title="新增用户" width="500">
    <el-form :model="form">
      <el-form-item label="用户名称" :label-width="formLabelWidth">
        <el-input v-model="form.username" autocomplete="off" />
      </el-form-item>
       <el-form-item label="密码" :label-width="formLabelWidth">
                    <el-input v-model="form.password" show-password>
                    </el-input>
        </el-form-item>
         <el-form-item label="姓名" :label-width="formLabelWidth">
                    <el-input v-model="form.name" />
        </el-form-item>
       <el-form-item label="选择角色" :label-width="formLabelWidth">
        <el-checkbox-group v-model="form.roleId">
           <el-checkbox name="type" v-for="a in Bind" :value="a.id">
                            {{ a.roleName }}
            </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="用户状态" :label-width="formLabelWidth">
        <el-switch
          v-model="form.state"
          active-text="启用"
          inactive-text="禁用"
          :active-value="true"
          :inactive-value="false"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="add()">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>

   <!-- 编辑 -->
    <el-dialog v-model="dialogFormVisible2" title="编辑用户" width="500">
    <el-form :model="form2">
      <el-form-item label="用户名称" :label-width="formLabelWidth">
        <el-input v-model="form2.username" autocomplete="off" />
      </el-form-item>
       <el-form-item label="密码" :label-width="formLabelWidth">
                    <el-input v-model="form2.password" show-password/>
        </el-form-item>
         <el-form-item label="姓名" :label-width="formLabelWidth">
                    <el-input v-model="form2.name" />
        </el-form-item>
       <el-form-item label="选择角色" :label-width="formLabelWidth">
        <el-checkbox-group v-model="form2.roleId">
           <el-checkbox name="type" v-for="a in Bind" :value="a.id">
                            {{ a.roleName }}
            </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="用户状态" :label-width="formLabelWidth">
        <el-switch
          v-model="form2.state"
          active-text="启用"
          inactive-text="禁用"
          :active-value="true"
          :inactive-value="false"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible2 = false">取消</el-button>
        <el-button type="primary" @click="update()">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 删除确认对话框 -->
  <el-dialog v-model="deleteDialogVisible" title="提示" width="300px" center>
    <div class="delete-dialog-content">
      <el-icon class="delete-icon"><WarningFilled /></el-icon>
      <span>确定要删除用户 "{{ currentDeleteItem?.name }}" 吗？</span>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete">确定</el-button>
      </div>
    </template>
  </el-dialog>

</template>

<script lang="ts" setup>
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { onMounted, ref, watch } from 'vue';
import { reactive } from 'vue';
import { Delete, WarningFilled } from '@element-plus/icons-vue';

import{getUser,addUser,updateUser,updateUserState,deleteUser,getRole} from'@/HTTPS/server'

onMounted(()=>{
    show();
    bind();
})

const formInline = reactive({
  name: '',
   pageIndex: 1,
  pageSize: 3,
})

const onSubmit = () => {
  console.log('submit!')
  show();
}

const pagin=ref({
    totaleCount:0,
    pageCount:0,
   
})

watch(formInline,()=>{
    show();
},{deep:true})

const tableData =ref([])
const show=()=>{
   getUser(formInline).then(res=>{
    tableData.value=res.data.data.list;
    pagin.value.pageCount=res.data.data.pageCount;
    pagin.value.totaleCount=res.data.data.totaleCount;
   })
}


//新增用户
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'

const form = reactive({
 "username": "",
  "password": "",
  "name": "",
  "roleId": [],
  "state": false
})

//获取角色列表
const Bind=<any>ref([])
const bind=()=>{
    getRole().then(res=>{
        Bind.value=res.data.data;
    })
}

const add=()=>{
    addUser(form).then(res=>{
        if(res.data.code==200){
            ElMessage.success(res.data.message);
            dialogFormVisible.value = false
            show();
        }else{
            ElMessage.error(res.data.message);
            return;
        }
    })
}

//编辑用户
const dialogFormVisible2 = ref(false)

const form2 = reactive({
    
    id:0,
  "username": "",
  "password": "",
  "name": "",
  "roleId": [],
  "state": false
})

const find=(row:any)=>{
    console.log(row)
    
     dialogFormVisible2.value = true
    form2.id=row.id;
    form2.username=row.username;
    form2.password=row.password;
    form2.name=row.name;
    form2.roleId=row.roleId;
    form2.state=row.state;
    console.log(form2);
}

const update=()=>{
 
    updateUser(form2).then(res=>{
     
        if(res.data.code==200){
            ElMessage.success(res.data.message);
            dialogFormVisible2.value = false
            show();
        }else{
            ElMessage.error(res.data.message);
            return;
        }
    })
}

// 删除用户
const deleteDialogVisible = ref(false);
const currentDeleteItem = ref<any>(null);

const handleDelete = (row: any) => {
  deleteDialogVisible.value = true;
  currentDeleteItem.value = row;
};

const confirmDelete = () => {
  if (!currentDeleteItem.value) return;
  
 deleteUser({ id: currentDeleteItem.value.id })
    .then(res => {
      if (res.data.code == 200) {
        ElMessage.success('删除成功');
        deleteDialogVisible.value = false;
        show(); // 刷新列表
      } else {
        ElMessage.error(res.data.message || '删除失败');
      }
    })
    .catch(error => {
      ElMessage.error('删除用户失败');
      console.error(error);
    });
};

// 处理用户状态变更
const handleStateChange = (row: any) => {
  const stateCommand = {
    id: row.id,
    state: row.state
  };
  
 updateUserState(stateCommand)
    .then(res => {
      if (res.data.code == 200) {
        ElMessage.success(`用户 "${row.name}" ${row.state ? '已启用' : '已禁用'}`);
      } else {
        // 如果更新失败，恢复之前的状态值
        row.state = !row.state;
        ElMessage.error(res.data.message || '状态更新失败');
      }
    })
    .catch(error => {
      // 如果请求异常，恢复之前的状态值
      row.state = !row.state;
      ElMessage.error('更新用户状态失败');
      console.error(error);
    });
};

</script>

<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>

<style scoped>
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}

.delete-dialog-content {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  padding: 16px 0;
}

.delete-icon {
  font-size: 24px;
  color: #f56c6c;
  margin-bottom: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>